﻿using System.Reflection;
using Microsoft.AspNetCore.Http;

namespace NanjingbeiRailwayStation.Core
{
    /// <summary>
    /// 临时
    /// </summary>
    public static class IFormFileExtention
    {
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        public static string Save(this IFormFile file,string path)
        {

            var fileName = file.FileName;
            string fileExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));//获取文件名称后缀 
                                                                                               //保存文件
            var stream = file.OpenReadStream();
            // 把 Stream 转换成 byte[] 
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            var newFileName = Guid.NewGuid().ToString() + fileExtension;
            // 把 byte[] 写入文件 

            var filePath=System.IO.Path.Combine(path, newFileName);

            FileStream fs = new FileStream(filePath, FileMode.Create);
            var bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            fs.Close();

            return newFileName;
        }
    }
}
